<template>
  <div>
    <el-upload ref="upload" v-model:file-list="fileList" :headers="{
      token
    }" :auto-upload="true" :data="data" name="fileUpload" :action="uploadUrl" list-type="picture-card" :limit="limit"
      :on-exceed="handleExceed" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="onSuccess"
      :on-error="onError">
      <el-icon>
        <Plus />
      </el-icon>

      <template #tip>
        <div class="el-upload__tip" v-if="tip">
          {{ tip }}
        </div>
      </template>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>


  </div>
</template>
<script setup lang="ts">
import { uploadUrl } from '@/api/upload'
import { getStorage } from '@/utils/storage'
import { message } from "@/utils/message";
import { genFileId } from 'element-plus'
import type { UploadProps, UploadUserFile, UploadInstance, UploadRawFile } from 'element-plus'
import { ref, withDefaults, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'

const token = getStorage('token')


interface ispic {
  ispic: string
}

interface Props {
  data?: ispic
  limit?: number
  modelValue: Array
  tip?: string
}

const props = withDefaults(defineProps<Props>(), {
  limit: 1,
  data: () => ({ ispic: '0' }),
  modelValue: () => [],
  tip: ''
})


console.log(props.data)

const emits = defineEmits(['success', "update:modelValue"])


const upload = ref<UploadInstance>()


const onSuccess = (response, uploadFile, uploadFiles) => {
  // emits('success', {
  //   response, uploadFile, uploadFiles
  // })
}



const onError = (error, uploadFile, uploadFiles) => {
  // console.log(JSON.parse(error.message).msg) || message("上传失败", {
  //   type: "error"
  // });
}
const fileList = ref<UploadUserFile[]>([...props.modelValue])


const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  // upload.value!.clearFiles()
  fileList.value.shift()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}


watch(fileList, newValue => emits("update:modelValue", newValue), {
  deep: true
});

</script>